Writing Health Quantity Samples

The Scripting app allows you to write quantity-based health data (such as step count, heart rate, calories, and more) to Apple HealthKit using the HealthQuantitySample class and the Health.saveQuantitySample method.

This guide explains how to create and save a new quantity sample.

Prerequisites

  • Ensure HealthKit is available on the device:

    1if (!Health.isHealthDataAvailable) {
    2  throw new Error("Health data is not available on this device.")
    3}
  • Make sure your script has the appropriate write permission for the quantity type you want to save. Permissions are requested automatically when you call save APIs.

1. Create a HealthQuantitySample

Use HealthQuantitySample.create() to instantiate a new sample.

Parameters

  • type: A HealthQuantityType string, such as "stepCount", "heartRate", "bodyMass", etc.
  • startDate: The start of the measurement period (a JavaScript Date object).
  • endDate: The end of the measurement period (a JavaScript Date object).
  • value: The numeric value of the sample.
  • unit: A HealthUnit representing the measurement unit (e.g., HealthUnit.count(), HealthUnit.gram(), HealthUnit.meter()).
  • metadata (optional): An object containing additional metadata.

Example

1const sample = HealthQuantitySample.create({
2  type: "stepCount",
3  startDate: new Date("2025-07-03T08:00:00"),
4  endDate: new Date("2025-07-03T09:00:00"),
5  value: 1200,
6  unit: HealthUnit.count(),
7  metadata: {
8    source: "ScriptingApp"
9  }
10})
11
12if (!sample) {
13  throw new Error("Failed to create HealthQuantitySample.")
14}

2. Save the Quantity Sample

After creating the sample, use Health.saveQuantitySample() to store it in the HealthKit database.

1await Health.saveQuantitySample(sample)

If saving fails (e.g., due to missing permissions), the promise will reject with an error.

Full Example

1async function writeStepCount() {
2  const sample = HealthQuantitySample.create({
3    type: "stepCount",
4    startDate: new Date("2025-07-03T08:00:00"),
5    endDate: new Date("2025-07-03T09:00:00"),
6    value: 1200,
7    unit: HealthUnit.count(),
8  })
9
10  if (!sample) {
11    console.error("Failed to create sample.")
12    return
13  }
14
15  try {
16    await Health.saveQuantitySample(sample)
17    console.log("Step count saved successfully.")
18  } catch (err) {
19    console.error("Failed to save sample:", err)
20  }
21}
22
23writeStepCount()

Notes

  • The unit must match the type. For example:

    • "stepCount"HealthUnit.count()
    • "bodyMass"HealthUnit.gram(HealthMetrixPrefix.kilo)
    • "heartRate"HealthUnit.count().divided(HealthUnit.minute())
  • If the sample’s type is cumulative (e.g., steps, distance), the startDate and endDate should cover the time window over which the value was measured.